package com.dfk.bs.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dfk.bs.common.vo.R;
import com.dfk.bs.entity.User;
import com.dfk.bs.entity.vo.WxSession;
import com.dfk.bs.service.UserService;
import com.dfk.bs.service.admin.WxSessionService;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.URI;

/**
 * @author smileyan
 */
@RestController
@RequestMapping("/wechat")
public class WeChatLoginController {

    @Autowired
    WxSessionService wxSessionService;

    @Autowired
    UserService userService;

    private static String appid = "wx6727839bea2a88bb";

    private static String appsecret = "0ba44b5bc256645880b9ee3119acd37f";

    private WxSession wxSessionAll;

    @PostMapping("/login/{code}")
    private R login(@PathVariable("code") String code, @RequestBody WxSession wxSession) {
        wxSessionAll = wxSession;
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + appsecret + "&js_code=" + code + "&grant_type=authorization_code";
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("resultString=====" + resultString);
        // 解析json
        JSONObject jsonObject = (JSONObject) JSONObject.parse(resultString);
        WxSession one = wxSessionService.getOne(Wrappers.<WxSession>lambdaQuery()
                .eq(WxSession::getOpenid, jsonObject.get("openid") + ""), false
        );
        if (one == null) {
            //如果这个微信没登陆过 就插入数据库  注册
            wxSession.setSession_key(jsonObject.get("session_key") + "");
            wxSession.setOpenid(jsonObject.get("openid") + "");
            return R.ok().message("微信注册成功").data("user", wxSession);
        }
        return R.ok().message("微信登陆成功").data("user", one);
    }

    @PostMapping("/bdhousecode")
    private R bdhousecode(@RequestBody JSONObject json) {
        String username = json.getString("username");
        String password = json.getString("password");
        String housecode = json.getString("housecode");
        String openid = wxSessionAll.getOpenid();
        //查询判断  业主中是否有相应信息  这样直接确保了不会出现误差(业主表已经进行规范了)
        User one = userService.getOne(
                Wrappers.<User>lambdaQuery()
                        //想着判断之前没人绑定的
                        //.isNull(User::getOpenid)
                        .eq(User::getHousecode, housecode)
                        .eq(User::getUsername, username)
                        .eq(User::getPassword, password), false
        );
        //System.out.println("one................"+one);
        if (one == null) {
            return R.error().message("验证信息有误");
        }
        String openidUser = one.getOpenid();
        if (openidUser.equals("")) {


            wxSessionAll.setHousecode(housecode);
            wxSessionService.save(wxSessionAll);
            one.setOpenid(openid);
            userService.updateById(one);

            return R.ok().message("绑定成功").data("user", wxSessionAll);

        }
        return R.error().message("房间已绑定用户");
    }

}
